//
//  ProductDetail_Vc.swift
//  Pods
//
//  Created by eme on 2017/3/27.
//
//

/*
 owner:cy
 update:2017年03月27日17:31:32
 info: 商品详情
 */
import RxSwift
import UtilCore
import RickonCore
import WebViewJavascriptBridge
import NetWorkCore
import ModelProtocol
import AddCarCore
import URLNavigator
import Kingfisher
import SwiftyJSON
import BrandonCore

class ProductDetail_Vc: Base_Vc,AddCarProtocol {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var productDetail_Wv: UIWebView!
    // 电话
    @IBOutlet weak var tel_Btn: UIButton!
    // 收藏
    @IBOutlet weak var collect_Btn: UIButton!
    // 进货单
    @IBOutlet weak var jhd_Btn: BadgeBtn!
    // 添加进货单
    @IBOutlet weak var addCart_Btn: UIButton!
    // 立即订购
    @IBOutlet weak var ljdg_Btn: UIButton!
    
    /// 显示已售罄stock == 0 && pdstate != 3 ,pdstate != 3 显示  失效， stock == 0 表示 售罄
    @IBOutlet weak var sellOut_Btn: UILabel!
    
    /*----------------------------   自定义属性区域    ----------------------------*/
    var bridge:WebViewJavascriptBridge?
    var pdid:String?
    var manageVm:ProductDetail_Vm?
    ///更新进货单数量
    var updateBadgeVm = UpdateBadge_Vm()
    var isReload:Bool = false
    var productModel:ProductModel?{
        didSet{
            if let productModel = self.productModel {
                self.collect_Btn.isSelected = productModel.cid.characters.count > 0
                if productModel.stock == 0 || productModel.pdstate != "3" {
                    if productModel.pdstate != "3" {
                        self.sellOut_Btn.text = "已失效"
                    }else{
                        self.sellOut_Btn.text = "已售罄"
                    }
                    self.sellOut_Btn.isHidden = false
                    self.addCart_Btn.isEnabled = false
                    self.ljdg_Btn.isEnabled = false
                }else{
                    self.sellOut_Btn.isHidden = true
                    self.addCart_Btn.isEnabled = productModel.buy == 1
                    self.ljdg_Btn.isEnabled = productModel.buy == 1
                }
            }
        }
    }
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.isReload {
            self.productDetail_Wv.reload()
            self.isReload = false
        }
        /// 获取进货单数量
        self.updateBadgeVm.updateSubject.onNext()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        self.tabBarController?.tabBar.isHidden = true
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        NotificationCenter.default.addObserver(self, selector: #selector(ProductDetail_Vc.updateBadgeBtnCount(_:)), name: NSNotification.Name(rawValue: AppConfig.notification.updateBadgeBtnCountKey), object: nil)
        /// 禁止twebview长按
        self.productDetail_Wv.dataDetectorTypes = .all
        WebViewJavascriptBridge.enableLogging()
        self.bridge = WebViewJavascriptBridge(forWebView: self.productDetail_Wv)
        self.bridge?.setWebViewDelegate(self)
        //注册js 事件
        registerHander()
        reloadwebView()
    }
    /**
     app 主题 设置
     */
    override func setViewTheme(){
        self.tel_Btn.changeEdgeVertical(8)
        self.collect_Btn.changeEdgeVertical(5)
        self.jhd_Btn.changeEdgeVertical(12)
        self.addCart_Btn.backgroundColor = UIColor.clear
        self.ljdg_Btn.backgroundColor = UIColor.clear
        self.addCart_Btn.changeBackgroundImage(Theme.robb.productDetail.addCart_normal, highlightedColor: Theme.robb.productDetail.addCart_highlighted, disabledColor: Theme.robb.productDetail.addCart_disabled)
        self.ljdg_Btn.changeBackgroundImage(Theme.robb.productDetail.ljdg_normal, highlightedColor: Theme.robb.productDetail.ljdg_highlighted, disabledColor: Theme.robb.productDetail.ljdg_disabled)
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        
        self.manageVm = ProductDetail_Vm(refreshTriger:Observable.just().map { _ in () }.filter{ _ in
            self.pdid != nil
            
            }.map{self.pdid!})
        self.manageVm?.loading.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        self.manageVm?.error.asObserver().bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        self.manageVm?
            .productItem
            .do(onNext: {[unowned self] (_) in
                self.errorPageView.isHidden = true
            })
            .subscribe{[unowned self] model  in
                self.productModel  = model.element
            }.disposed(by: disposeBag)
        self.manageVm?
            .addcartsSuccess
            .subscribe(onNext: {[unowned self] (rel) in
                /// 获取进货单数量
                self.updateBadgeVm.updateSubject.onNext()
                showMsg(100041002)
            }).disposed(by: disposeBag)
        self.collect_Btn.rx.tap
            .auth_validation("0")
            .subscribe(onNext: {[unowned self] (isok) in
                if let productModel = self.productModel,isok{
                    /// 表示已经收藏
                    if self.collect_Btn.isSelected{
                        self.manageVm?.delusPdCollectionSubject.onNext(productModel.cid)
                    }else{
                        ///表示 未收藏
                        if let user  = AppData.loginedUser {
                            self.manageVm?.addusPdCollectionSubject.onNext((userid: user.userid, pdid:"\(productModel.pdid)"))
                        }
                    }
                }
            }).disposed(by: disposeBag)
        self.manageVm?
            .pdCollectionSuccess
            .subscribe(onNext: {[unowned self] (cid) in
                self.collect_Btn.isSelected = cid.characters.count > 0
                self.productModel?.cid = cid
            }).disposed(by: disposeBag)
        self.errorPageView
            .reloadSubject
            .subscribe(onNext: {[unowned self] (_) in
                self.reloadwebView()
            })
            .disposed(by: disposeBag)
        self.errorPageView
            .reloadSubject
            .bindTo(self.manageVm!.reloadTrigger)
            .disposed(by: disposeBag)
        self.updateBadgeVm
            .updateSuccess
            .subscribe(onNext: {[unowned self] (count) in
                self.jhd_Btn.badgeCount = count
            })
            .disposed(by: disposeBag)
        self.addCart_Btn
            .rx.tap
            .auth_validation()
            .subscribe(onNext: { [unowned self] ( isok ) in
                if let productmodel = self.productModel, isok{
                    self.addCar(vc: self, model: productmodel,footerButonType:"jrphd"){ product , param,_ in
                        self.manageVm?.addcartsSubject.onNext(param["osCarts"] as! String as NSString)
                    }
                }
            })
            .disposed(by: disposeBag)
        self.ljdg_Btn
            .rx.tap
            .auth_validation()
            .subscribe(onNext: { [unowned self] ( isok ) in
                if let productmodel = self.productModel,isok{
                    self.addCar(vc: self, model: productmodel,footerButonType:"ljdg"){ product , param ,_ in
                        _ = "cofirmorder".openURL(["osCarts":param["osCarts"] as! String,"ismix":param["ismix"] as? String ?? "0","iscart":"0"])
                    }
                }
            })
            .disposed(by: disposeBag)
        self.jhd_Btn
            .rx.tap
            .auth_validation()
            .subscribe(onNext: { ( isok ) in
                if isok{
                    _ =  "orderform".openURL()
                }
            })
            .disposed(by: disposeBag)
        self.tel_Btn
            .rx.tap
            .auth_validation()
            .subscribe(onNext: { [unowned self] ( isok ) in
                if let model = self.productModel,isok{
                    _ = "callbyphone".openURL(["phone":model.agmobile])
                }
            })
            .disposed(by: disposeBag)
        NotificationCenter
            .default
            .rx
            .notification(Notification.Name(rawValue: AppConfig.notification.appdatachangedKey), object: nil)
            .takeUntil(rx.methodInvoked(#selector(viewWillDisappear(_:))))
            .subscribe(onNext: { [unowned self] ( _ ) in
                self.reloadwebView()
            })
            .disposed(by: disposeBag)
        
    }
    
    
    
}
extension ProductDetail_Vc{
    func reloadwebView() -> Void {
        if let pdid = self.pdid {
            var url = UrlManager.sharedInstance.baseUrl + "/glProduct/view.html" + "?pdid=\(pdid)"
            if let user = AppData.loginedUser,user.glShop.spareacode.characters.count > 0 {
                url = url + "&areacode=\(user.glShop.spareacode!)"
            }
            self.view.showLoading()
            if let url = URL(string: url) {
                var request = URLRequest(url: url )
                request.setValue(UtilCore.sharedInstance.devid, forHTTPHeaderField:"devid")
                self.productDetail_Wv.loadRequest(request as URLRequest)
            }
        }
    }
    /// 更新进货单图标
    func updateBadgeBtnCount(_ notification: NSNotification) {
        if  let rel = notification.object as? String {
            self.jhd_Btn.badgeCount = Int(rel) ?? 0
        }
    }
    /*
     更新按钮的点击状态显示
     1.当按钮售罄 或者失效 不可点击
     2.在秒杀商品时 如果没有开始抢购 则为不可能点击
     */
    func updateBtnState(buy:Bool) {
        self.ljdg_Btn.isEnabled = buy
    }
    ///给js 注册监听
    func registerHander() {
        //服务器加载完毕后 需要关闭遮罩
        self.bridge?.registerHandler("closeLoading", handler:{  data , response in
            self.view.hideLoading()
        })
        //打开原生界面（商品详情） web -> app -> openProduct,参数：{pdid:,areacode:},无返回
        self.bridge?.registerHandler("chooseSku", handler:{  data , response in
            if "authvalidation".openURL(["isneedlogin":"1"]){
                ///表示已经审核通过了，可以购买
                if let productModel = self.productModel{
                    if productModel.istimeby == "1"{
                        /// 如果是秒杀类型的商品则 弹出的只有立即订购按钮
                        self.addCar(vc: self, model: productModel,footerButonType:"ljdg"){ product , param ,_ in
                            _ = "cofirmorder".openURL(["osCarts":param["osCarts"] as! String,"ismix":param["ismix"] as? String ?? "0","iscart":"0"])
                        }
                    }else{
                        self.addCar(vc: self, model: self.productModel!,footerButonType:""){ product , param,clicktype in
                            if clicktype == "jrphd"{
                                self.manageVm?.addcartsSubject.onNext(param["osCarts"] as! String as NSString)
                            }else{
                                _ = "cofirmorder".openURL(["osCarts":param["osCarts"] as! String,"ismix":param["ismix"] as? String ?? "0","iscart":"0"])
                            }
                            
                        }
                    }
                    
                }
            }
        })
        self.bridge?.registerHandler("setBuy", handler:{  data , response in
            if let data = data{
                let json = JSON(object: data)
                self.updateBtnState(buy: json["state"].intValue == 1)
            }
        })
        self.bridge?.registerHandler("error", handler:{  data , response in
            if let data = data{
                let json = JSON(object: data)
                let message = json["message"].stringValue
                let status = json["status"].intValue
                if status == 201003{
                    self.isReload = true
                }
                self.view.toastError(MikerError("status", code: status, message: message))
            }
        })
        //打开原生界面（商品详情） web -> app -> openProduct,参数：{pdid:},无返回
        self.bridge?.registerHandler("savePhotoByKey", handler:{  data , response in
            if let data = data{
                let json = JSON(object: data)
                self.savePhoto(photoKey: json["key"].stringValue)
            }
        })
        //打开原生界面（商品详情） web -> app -> openProduct,参数：{pdid:},无返回
        self.bridge?.registerHandler("openProduct", handler:{  data , response in
            if let data = data{
                let json = JSON(object: data)
                _ =  "productdetail".openURL(["pdid":"\(json["pdid"].stringValue)"])
            }
        })
        
        //打开原生界面（品牌详情） web -> app -> openBrand,参数：{brid:},无返回
        self.bridge?.registerHandler("openBrand", handler:{  data , response in
            if let data = data{
                let json = JSON(object: data)
                _ =  "brandpage".openURL(["brid":json["brid"].stringValue])
            }
        })
        //打开原生界面（抢购详情）web -> app -> openRpt,参数：{id:},无返回
        self.bridge?.registerHandler("openRpt", handler:{  data , response in
            if let data = data{
                let json = JSON(object: data)
                _ =  "miaosha".openURL(["id":json["rptid"].stringValue])
            }
        })
        //打开原生界面（商品详情）
        self.bridge?.registerHandler("openactivebyuri", handler:{  data , response in
            if let data = data{
                let json = JSON(object: data)
                _ = json["uri"].stringValue.openURL()
            }
        })
        //打开原生界面（组合商品列表） web -> app -> openGroup,参数：{pdid:,areacode:},无返回
        self.bridge?.registerHandler("openGroup", handler:{  data , response in
            if let productModel = self.productModel{
                _ = "OrderGroup".openURL(["pdid":"\(productModel.pdid)","orderid":""])
            }
        })
        //打开原生界面（组合商品列表） web -> app -> openGroup,参数：{pdid:,areacode:},无返回
        self.bridge?.registerHandler("authinfo", handler:{  data , response in
            _ = "authvalidation".openURL(["isneedlogin":"1"])
            
        })
    }
    ///保存图片到相册
    func savePhoto(photoKey:String)
    {
        let savePhotoAlert = UIAlertController(title: "保存到相册", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
        let okAction = UIAlertAction.init(title: "确定", style: UIAlertActionStyle.default, handler: { UIAlertAction in
            if let photoUrl = URL(string: photoKey.ImgUrl()){
                ImageDownloader.default.downloadImage(with: photoUrl, options: nil, progressBlock: nil, completionHandler: { (image, error, imageURL, originalData) in
                    if let image = image{
                        UIImageWriteToSavedPhotosAlbum(image, self, #selector(ProductDetail_Vc.image(_:didFinishSavingWithError:contextInfo:)), nil)
                    }else{
                        self.view.toast("保存失败!")
                    }
                })
            }
        })
        let canelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel,handler: nil)
        savePhotoAlert.addAction(canelAction)
        savePhotoAlert.addAction(okAction)
        self.present(savePhotoAlert, animated: true, completion: nil)
    }
    func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafeRawPointer) {
        if error == nil {
            self.view.toast("保存成功!")
        } else {
            self.view.toast("保存失败!")
        }
    }
}
extension ProductDetail_Vc :UIWebViewDelegate{
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        return true
    }
    func webViewDidStartLoad(_ webView: UIWebView){
        
    }
    func webViewDidFinishLoad(_ webView: UIWebView){
        self.view.hideLoading()
    }
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error){
        if let emptyView = self.view.viewWithTag(UtilCore.ErrorPageViewTag) {
            emptyView.isHidden = false
        }else{
            
            self.errorPageView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
            self.view.addSubview(self.errorPageView)
        }
        
        self.view.hideLoading()
    }
}
